import glob
import importlib
import os
from enums import parse_dict_enum
from enums.custom import CustomDictService
from packages.engine.util.reflect_util import ReflectUtil
from tools import underline_to_hump


class LoadEnum:
    """
    加载字典
    """

    def __init__(self, app=None):
        self.app = app
        if app:
            self.init_app(app)

    def init_app(self, app):
        self.app = app
        if "DICT_ENUM_MAP" not in app.config:
            app.config["DICT_ENUM_MAP"] = {}
        if "DICT_ENUM_LIST" not in app.config:
            app.config["DICT_ENUM_LIST"] = []
        if "DICT_CUSTOM_LIST" not in app.config:
            app.config["DICT_CUSTOM_LIST"] = []
        # 获取controllers目录下所有的.py文件路径
        enums_dir = "enums"
        enum_files = glob.glob(os.path.join(enums_dir, "*.py"))
        # 过滤掉__init__.py文件
        enum_files = [
            f
            for f in enum_files
            if ("__init__.py" not in f and "load_enum.py" not in f)
        ]
        for file_path in enum_files:
            module_name = os.path.splitext(os.path.basename(file_path))[
                0
            ]  # 去掉'.py'后缀
            module_path = f"enums.{module_name}"
            try:
                enum_module = importlib.import_module(module_path)
                enumClass = getattr(enum_module, underline_to_hump(module_name))
                enumData = parse_dict_enum(enumClass)
                dictKey = enumData.get("dictKey")
                app.config["DICT_ENUM_MAP"].update({dictKey: enumData})
                app.config["DICT_ENUM_LIST"].append(enumData)
            except (ImportError, AttributeError) as e:
                print(f"Failed to load model {module_name}: {e}")

        # 处理自定义字典类
        classList = ReflectUtil.find_class_from_dirs(
            "enums/custom/impl", CustomDictService
        )
        for clazz in classList:
            customDictService: CustomDictService = clazz()
            dictModel = customDictService.get_dict_model()
            app.config["DICT_ENUM_MAP"].update({dictModel.get("dictKey"): dictModel})
            app.config["DICT_CUSTOM_LIST"].append(dictModel)
